<?php

#<editor-fold defaultstate="collapsed" desc="CCore::Using">
CCore::Using('base.collection');
#</editor-fold>

class CCoreMimeParameter
{
	#<editor-fold defaultstate="collapsed" desc="private">
	/**
	 * @var	string
	 */
	private $_sName;

	/**
	 * @var	string
	 */
	private $_sValue;
	#</editor-fold>

	/**
	 * @param	string	$sName = ''
	 * @param	string	$sValue = ''
	 * @return	CCoreMimeParameter
	 */
	public function __construct($sName = '', $sValue = '')
	{
		CCore::CheckTypes(array('$sName', '$sValue'));
		
		$this->_sName = $sName;
		$this->_sValue = $sValue;
	}

	/**
	 * @return	string
	 */
	public function Name()
	{
		return $this->_sName;
	}

	/**
	 * @return	string
	 */
	public function Value()
	{
		return $this->_sValue;
	}

	/**
	 * @param	string	$sRawParam
	 * @param	string	$sSeparator = '='
	 * @return	void
	 */
	public function Parse($sRawParam, $sSeparator = '=')
	{
		CCore::CheckTypes(array('$sRawParam', '$sSeparator'));
		
		$aParts = explode($sSeparator, $sRawParam, 2);

		$this->_sName = trim(trim($aParts[0]), '"\'');
		if (count($aParts) == 2)
		{
			$this->_sValue = trim(trim($aParts[1]), '"\'');
		}
	}
}

class CCoreMimeParametersCollection extends ACoreBaseCollection
{
	/**
	 * @param	string	$nsRawParams = null
	 * @return	CCoreMimeParametersCollection
	 */
	public function __construct($nsRawParams = null)
	{
		CCore::CheckTypes(array('$nsRawParams'));
		
		parent::__construct();
		
		if (null !== $nsRawParams)
		{
			$this->_parse($nsRawParams);
		}
	}

	/**
	 * @param	string	$sName
	 * @return	string
	 */
	public function GetParamValueByName($sName)
	{
		CCore::CheckTypes(array('$sName'));

		$aParams =& $this->GetArray();
		foreach ($aParams as $aParam)
		{
			if (strtolower($sName) === strtolower(trim($aParam->Name())))
			{
				return $aParam->Value();
			}
		}
		return '';
	}

	/**
	 * @return	string
	 */
	public function GetFirstParam()
	{
		$aParams =& $this->GetArray();
		return isset($aParams[0]) ? $aParams[0] : '';
	}

	/**
	 * @param	CCoreMimeParameter	$oMimeParameter
	 * @return	void
	 */
	public function Add(CCoreMimeParameter $oMimeParameter)
	{
		CCore::CheckTypes(array('$oMimeParameter'));

		parent::Add($oMimeParameter);
	}
	
	/**
	 * @param	string	$sDataToParse
	 * @return	void
	 */
	private function _parse($sDataToParse)
	{
		CCore::CheckTypes(array('$sDataToParse'));
		
		$aDataToParse = explode(';', $sDataToParse);

		foreach ($aDataToParse as $sParam)
		{
			$oMimeParameter = new CCoreMimeParameter();
			$oMimeParameter->Parse($sParam);
			$this->Add($oMimeParameter);
			unset($oMimeParameter, $sParam);
		}
	}
}